package com.dhecp.project.purchase.service.impl;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.purchase.domain.PurchasePlanCancel;
import com.dhecp.project.purchase.domain.PurchasePlanCancelSon;
import com.dhecp.project.purchase.mapper.PurchasePlanCancelMapper;
import com.dhecp.project.purchase.mapper.PurchasePlanCancelSonMapper;
import com.dhecp.project.purchase.service.PurchasePlanCancelService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program: kjecp
 * @description: 采购计划取消
 * @author: hlf
 * @create: 2022-08-20 09:52
 */
@Service
public class PurchasePlanCancelServiceImpl extends BaseModuleServiceImpl implements PurchasePlanCancelService {


    @Autowired
    private PurchasePlanCancelMapper purchaseMapper;
    @Autowired
    private PurchasePlanCancelSonMapper sonMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;


    /**
     *@Description: 查询前一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult  (data.nid 前一单NID， data.bid 前一单BID)
     *@Author: hlf
     *@date: 2022-05-09 10:08
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == ""){
            params.put("nid", "0");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = purchaseMapper.selectLastNid(params);
        if (moduleNID == null){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     *@Description: 查询后一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult  (data.nid 后一单NID， data.bid 后一单BID)
     *@Author: hlf
     *@date: 2022-05-09 10:09
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = purchaseMapper.selectNextNid(params);
        if (moduleNID == null){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }



    @Override
    public PurchasePlanCancel queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return purchaseMapper.selectFirstRecordByNid(params);
    }

    @Override
    public List<PurchasePlanCancel> queryListByNid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return purchaseMapper.selectByNid(params);
    }

    @Override
    public List<PurchasePlanCancel> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return purchaseMapper.select(params);
    }

    @Override
    public List<PurchasePlanCancelSon> querySonListBm(Map<String, Object> params) throws Exception {
        return sonMapper.queryListBm(params);
    }

    @Override
    public List<PurchasePlanCancelSon> querySonListNid(String fNid) throws Exception {
        return sonMapper.queryListNid(fNid);
    }


    @Override
    public List<PurchasePlanCancel> queryGroupList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return purchaseMapper.selectgroup(params);
    }

    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult saveData(Map<String, Object> params) {
        params.put("businessEntity", new PurchasePlanCancel());
//        params.put("isAuto", false);
        AjaxResult ajaxResult = this.saveDataBase(params);

        Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        String resNid = infoMap.get("nid").toString();

        PurchasePlanCancel onData = JSON.parseObject(params.get("infoMap").toString(), PurchasePlanCancel.class);
        List<PurchasePlanCancel> purchasePlanList = JSON.parseArray(params.get("infoItems").toString(), PurchasePlanCancel.class);
        List<PurchasePlanCancelSon> onSonData = new ArrayList<>();
        if (params.containsKey("sonData")){
            onSonData = JSON.parseArray(params.get("sonData").toString(), PurchasePlanCancelSon.class);
        }
        List<RecordCheck> guidMapList = purchaseMapper.findRecords(infoMap.get("nid").toString());

        Map<String, Object> guidMap = new HashMap<String, Object>();
        if (!guidMapList.isEmpty()){
            if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())){ //单号重复验证
                throw new RuntimeException(MessageUtils.message("module.error.retry"));
            }
            for (RecordCheck recordCheck : guidMapList){
                if (recordCheck != null && recordCheck.getGuid() != null){
                    guidMap.put(recordCheck.getGuid().toString(), "1");
                }
            }
        }
        if (purchasePlanList == null || purchasePlanList.size() == 0){
            resNid = "0";
        }else{
            resNid = infoMap.get("nid").toString();
            for (PurchasePlanCancel item : purchasePlanList) {
                String guid = "";
                if (Objects.equals(resNid, "0")){
                    guid = RandomValueUtils.getGUID();
                    item.setGuid(guid);
                }else{
                    guid = item.getGuid().toString();
                }

                for (String field : infoMap.keySet()) { //遍历非网格字段，并赋值到实体中
                    Object fieldValue = infoMap.get(field);
                    ReflectUtils.setValue(item, field, fieldValue);
                }

                if (guidMap.get(guid) == null){
                    purchaseMapper.insert(item);
                }else{
                    purchaseMapper.update(item);
                    guidMap.remove(guid);
                }
            }

            List<PurchasePlanCancelSon> lodData = sonMapper.queryListNid(resNid);
            if (lodData.size()>0){
                for (PurchasePlanCancelSon item : lodData
                ) {
                    sonMapper.delete(item);
                }
            }

            for (PurchasePlanCancelSon item : onSonData
            ) {
                item.setGuid(RandomValueUtils.getGUID());
                item.setCreateTime(new Date());
                item.setfNid(resNid);
                sonMapper.insert(item);
            }

        }

        if (!guidMap.isEmpty()){
            for (String guid : guidMap.keySet()){
                purchaseMapper.delete(guid);
            }
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), resNid);
    }


    /**
     * 修改审核状态
     *
     * @param guid
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateType(Map<String, Object> params) {
        List<PurchasePlanCancel> purchasePlanCancels = purchaseMapper.findByIdList(params);
        for (PurchasePlanCancel item:purchasePlanCancels
        ) {
            item.setvType(Integer.valueOf(params.get("vType").toString()));
            item.setUpdateTime(new Date());
            purchaseMapper.update(item);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }


    /**
     * 删除采购取消数据
     * @param nid
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult delete(Map<String, Object> params) {
        purchaseMapper.deleteNid(params.get("nid").toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }



    /**
     *@Description: 流转  —— 添加流程任务、修改流程状态及生效标志
     *@Param: [params] tableDataId 必要参数：单据编码（nid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
            return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
        }else{
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<PurchasePlanCancel> businessDataList = purchaseMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0){
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        }else{
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == ""){
            params.put("optType", "go");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (PurchasePlanCancel businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            purchaseMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     *@Description: 退回  —— 添加流程任务、修改流程状态及生效标志
     *@Param: [params] tableDataId 必要参数：单据编码（nid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
            return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
        }else{
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<PurchasePlanCancel> businessDataList = purchaseMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0){
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        }else{
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == ""){
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (PurchasePlanCancel businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            purchaseMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

}